package thread;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class IsAnagram {
    public boolean isAnagram2(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        char[] str1 = s.toCharArray();
        char[] str2 = t.toCharArray();
        Arrays.sort(str1);
        Arrays.sort(str2);
        return Arrays.equals(str1, str2);
    }


    boolean isAnagram(String s, String t) {
        if (s.equals(t)) {
            return true;
        }

        char[] s1 = s.toCharArray();
        char[] s2 = t.toCharArray();

        Map<String, Integer> s1Maps = countTimes(s1);
        Map<String, Integer> s2Maps = countTimes(s2);

        int s1MapsSize = s1Maps.size();
        int s2MapsSize = s2Maps.size();

        if (s1MapsSize > s2MapsSize) {
            return getResult(s1Maps, s2Maps);
        } else {
            return getResult(s2Maps, s1Maps);
        }
    }

    boolean getResult(Map<String, Integer> s1Maps, Map<String, Integer> s2Maps) {
        for (Map.Entry<String, Integer> entry : s1Maps.entrySet()) {
            String key = entry.getKey();
            int s1Times = entry.getValue();

            if (s2Maps.containsKey(key)) {
                int s2Times = s2Maps.get(key);
                if (s1Times != s2Times) {
                    return false;
                }
            } else {
                return false;
            }
        }

        return true;
    }

    Map<String, Integer> countTimes(char[] ary) {
        Map<String, Integer> result = new HashMap<>();

        for (char val : ary) {
            String str = String.valueOf(val);

            if (result.containsKey(str)) {
                int times = result.get(str) + 1;
                result.put(str, times);
            } else {
                result.put(str, 1);
            }
        }

        return result;
    }

    public static void main(String[] args) {
        String s = "a";
        String t = "ab";

        IsAnagram isAnagram = new IsAnagram();
        System.out.println(isAnagram.isAnagram(s, t));

        System.out.println(isAnagram.isAnagram2("a", "ab"));
    }
}
